<template>
  <div class="music-player">
    <el-row>
      <el-col :span="24">
        <audio ref="audio" controls @timeupdate="updateProgress" @loadedmetadata="setDuration" style="display: none;">
          <source v-for="(src, index) in audioSources" :key="index" :src="src" type="audio/mpeg">
          您的浏览器不支持 audio 元素。
        </audio>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="5">
        <div class="controls" style="height: 80px; display: flex; align-items: center; justify-content: center;">
          <el-button class="buttonControll" @click="togglePlay" :icon="isPlaying ? 'el-icon-video-pause' : 'el-icon-video-play'" circle style="height: 40px"></el-button>
        </div>
      </el-col>
      <el-col :span="18">
        <p class="headerWord">{{ currentWord }}</p>
        <el-slider v-model="progress" :max="duration" @change="seek" class="progress-bar" :format-tooltip="formatTooltip"></el-slider>
        <span class="time">{{ formattedCurrentTime }} / {{ formattedDuration }}</span>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div>
          <button @click="toggleLyricsVisibility" class="toggle-lyrics-button">
            {{ showLyrics ? '隐藏歌词' : '显示歌词' }}
          </button>
        </div>
        <div class="lyrics" ref="lyricsContainer" v-if="showLyrics">
          <p
            v-for="(line, index) in lyricsArray"
            :key="index"
            :class="{ 'active-line': isLyricActive(line.time) }"
            :ref="`lyric-${index}`"
            @click="seekToLyric(line.time)"
          >
            {{ line.text }}
          </p>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// import axios from 'axios';

export default {
  name: 'MusicPlayer',
  data() {
    return {
      progress: 0,
      duration: 0,
      isPlaying: false,
      currentTime: 0,
      audioSources: [],
      lyrics: {},
      activeLyricIndex: 0, // 当前活动的歌词索引
      lyricLineHeight: 0, // 歌词行的高度
      timer: null, // 定时器
      currentWord: '',
      clickTime: 0,
      lyricsArray: [], // 新增歌词数组
      showLyrics: false, // 新增显示歌词的标志
    };
  },
  computed: {
    formattedCurrentTime() {
      return this.formatTime(this.currentTime);
    },
    formattedDuration() {
      return this.formatTime(this.duration);
    },
    isLyricActive() {
      return (time) => {
        return this.currentTime >= time && this.currentTime < (this.lyricsArray[this.lyricsArray.findIndex(line => line.time === time) + 1] ? this.lyricsArray[this.lyricsArray.findIndex(line => line.time === time) + 1].time : this.duration);
      };
    }
  },
  methods: {
    updateProgress() {
      this.progress = this.$refs.audio.currentTime;
      this.currentTime = this.$refs.audio.currentTime;
      this.scrollToActiveLine(); // 确保调用 scrollToActiveLine 方法
    },
    setDuration() {
      this.duration = this.$refs.audio.duration;
    },
    seek(value) {
      this.$refs.audio.currentTime = value;
      this.updateTime();
    },
    togglePlay() {
      if (this.isPlaying) {
        this.$refs.audio.pause();
      } else {
        this.$refs.audio.play();
      }
      this.isPlaying = !this.isPlaying;
    },
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = Math.floor(seconds % 60);
      return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
    },
    formatTooltip(value) {
      return this.formatTime(value);
    },
    scrollToActiveLine() {
      const activeLine = this.lyricsArray.find(line => this.isLyricActive(line.time));
      if (!activeLine) return;
      const activeIndex = this.lyricsArray.findIndex(line => line.time === activeLine.time);
      if (activeIndex !== this.activeLyricIndex) {
        this.activeLyricIndex = activeIndex;
        const container = this.$refs.lyricsContainer;
        if (!container) return;
        container.scrollIntoView({
          behavior: 'smooth',
          block: 'center'
        });
        container.scrollTop = activeIndex * 14 * 2;
      }
    },
    seekToLyric(time) {
      this.$refs.audio.currentTime = time;
      if (!this.isPlaying) {
        this.togglePlay();
      }
    },
    updateTime() {
      this.currentTime = this.$refs.audio.currentTime;
      this.updateProgress();
      // 判断lyrics是否有当前时间对应的key值
      let keys = Object.keys(this.lyrics).map(Number).sort((a, b) => a - b);
      for (let i = keys.length - 1; i >= 0; i--) {
        if (this.currentTime >= keys[i]) {
          this.currentWord = this.lyrics[keys[i]];
          this.clickTime = keys[i];
          break;
        }
      }
    },
    loadAudioFiles() {
        const context = require.context('./music', false, /\.mp3$/);
        this.audioSources = context.keys().map(key => {
          try {
            const module = context(key);
            return module || ''; // 确保返回有效的音频文件路径
          } catch (error) {
            console.error(`Error loading audio file ${key}:`, error);
            return ''; // 返回空字符串以避免未定义值
          }
        }).filter(src => src); // 过滤掉无效的路径
        this.audioSources.forEach(src => {
          var fileName = src.split('/').pop().replace('.mp3', '');
          if (fileName.includes('.')) {
            fileName = fileName.split('.')[0];
          }
          this.loadLyricsFile(fileName);
        });
    },
    loadLyricsFile(fileName) {
        const lyricsPath = require(`./musicWord/${fileName}.json`);
        this.lyrics = lyricsPath;
        console.log(this.lyrics);
        this.lyricsArray = Object.entries(this.lyrics).map(([time, text]) => ({ time: parseFloat(time), text })).sort((a, b) => a.time - b.time);
    },
    toggleLyricsVisibility() {
      this.showLyrics = !this.showLyrics;
    }
  },
  mounted() {
    this.loadAudioFiles();
    this.loadLyricsFile('qianqian'); // 假设默认加载千千.json
    this.timer = setInterval(this.updateTime, 1000);
    this.currentWord = this.lyrics[0];
  },
  beforeDestroy() {
    clearInterval(this.timer);
  }
};
</script>

<style scoped>
.music-player {
  width: 100%; /* 设置宽度 */
  border-radius: 10px; /* 圆角 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 阴影 */
  background-color: #f9f9f9; /* 修改背景颜色为亮色 */
  padding: 0px;
  align-items: center;
}

.controls {
  margin-right: 10px; /* 添加右边距 */
}

.play-pause-button {
  padding: 5px 10px;
  border: none;
  border-radius: 5px;
  background-color: #409EFF;
  color: white;
  cursor: pointer;
  margin-right: 10px;
}

.play-pause-button:hover {
  background-color: #66b1ff;
}

.time {
  font-size: 14px;
  color: #333333; /* 修改文字颜色为暗色 */
}

.progress-bar {
  width: 100%;
}

.progress-bar >>> .el-slider__bar {
  background-color: rgba(0, 0, 0, 0.5); /* 修改进度条颜色为半透明黑色 */
  border-radius: 10px; /* 添加圆角 */
}

.progress-bar >>> .el-slider__runway {
  background-color: rgba(0, 0, 0, 0.2); /* 修改进度条轨道颜色为半透明黑色 */
  border-radius: 10px; /* 添加圆角 */
}

/* 添加歌词栏样式 */
.lyrics {
  margin-top: 10px;
  padding-top: 50%;
  width: 100%;
  height: 300px; /* 设置固定高度 */
  overflow: auto; 
  display: flex;
  flex-direction: column;
}

.lyrics p {
  margin: 0;
  padding: 0;
  font-size: 14px;
  line-height: 2; 
  color: #333333; /* 修改文字颜色为暗色 */
  cursor: pointer; /* 添加鼠标指针样式 */
}

.lyrics p.active-line {
  color: #409EFF;
}

/* 修改滚动条样式 */
.lyrics::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
}

.lyrics::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1); /* 滚动条轨道背景色 */
  border-radius: 10px; /* 圆角 */
}

.lyrics::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.5); /* 滚动条颜色 */
  border-radius: 10px; /* 圆角 */
}

.lyrics::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.7); /* 滚动条悬停颜色 */
}

.toggle-lyrics-button {
  padding: 5px 10px;
  border: none;
  border-radius: 5px;
  background-color: #409EFF;
  color: white;
  cursor: pointer;
  margin-bottom: 10px;
}

.toggle-lyrics-button:hover {
  background-color: #66b1ff;
}

.headerWord {
  margin: 0;
  padding: 0;
  font-size: 12px;
  color: #333333; /* 修改文字颜色为暗色 */
  line-height: 2; 
}

</style>